package Prova::Controller::TagMgr;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Data::Dumper;

=head1 NAME

Prova::Controller::TagMgr - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 create

create action

=cut

sub create : Private {
    my ( $self, $c, $test_case_id, $tags ) = @_;

    if ( ref $tags eq 'ARRAY' ) {
        # set tags before registing relations
        my @tag_ids;
        my %seen;
        for my $name ( @$tags ) {
            next if $seen{$name};
            my $tag = $c->forward( '/tags/find_by_name', [ $name ] );
            unless ( $tag ) {
                $tag = $c->forward( '/tags/create', [ $name ] );
            }
            $c->log->debug( "id: ".$tag->id );
            push @tag_ids, $tag->id;
            $seen{$name} = 1;
        }

        # relation
        my $relation = $c->forward( '/testcasestags/create', [ $test_case_id, \@tag_ids ] );
    }
}

=head2 get_tags

get tags action

=cut

sub get_tags : Private {
    my ( $self, $c, $test_case_id ) = @_;

    my @testcases_tags = $c->model( 'DBIC::TestcasesTags' )->search(
                                                                    test_case_id => $test_case_id
                                                                );
    my @tags;
    if ( @testcases_tags ) {
        for ( @testcases_tags ) {
            push @tags, $_->tags_id->name;
        }
    }

    return [ sort @tags ];
}

=head2 get_all_tags

get all tags action

=cut

sub get_all_tags : Private {
    my ( $self, $c ) = @_;

    my @testcases_tags = $c->model( 'DBIC::TestcasesTags' )->search({});
    my %ids;
    if ( @testcases_tags ) {
        for ( @testcases_tags ) {
            $ids{$_->test_case_id->id} = 1;
        }
    }
    foreach (keys %ids) {
        $c->session->{all_tags}->{$_} = $self->get_tags($c, $_);
    }
}

=head2 get_tag_rels

get tag relactions action

=cut

sub get_tag_rels : Private {
    my ( $self, $c, $tag_ids ) = @_;

    my @rels = $c->model( 'DBIC::TestcasesTags' )->search(
                                                          tags_id => $tag_ids
                                                      );
    return \@rels
}

=head1 AUTHOR

Shanon Inc, E<lt>http://www.shanon.co.jp/E<gt>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
